package controlGraph;

import java.util.ArrayList;

public class ConditionalGoto extends Statement {
	private int branchLabel;
	private Expression condition;
	private ArrayArith rules;
	private store zigma;

	
	public ConditionalGoto(String l, Expression c) {
		super();
		condition=c;
		labelName = l;
		
		//This statement is a branching statement
		//since the label is changed to the true branch
		//We shall store the false branch i.e. the previous label number
		//in branchLabel
		
		branchLabel = label;
	}
	
	public ConditionalGoto(int l, Expression c) {
		super();
		branchLabel = l;
		condition = c;
	}

	@Override
	public void visitSuccessors(store zigma, ArrayArith rules) {
		
		//This is for the branch - true
		
		this.zigma = new store(zigma);
		this.rules = new ArrayArith(rules);
		
		//workaround starts here
		Statement.zigma = this.zigma;
		Statement.rules = this.rules;
		//workaround ends here
		
		if((!(condition instanceof ArithExpr))|| (!((ArithExpr)condition).isValid())){
			System.out.println("Condition is not a instance of ArithExpr");
			System.exit(1);
		}
		
		ArithExpr actualRule = (ArithExpr)condition;
		//Statement.rules.addArith(actualRule);
		
		if(Statement.canBranch(actualRule)){
			
			Statement.rules.addArith(actualRule);
			System.out.println("True branch of ("+((ArithExpr)condition).getAxiomString()+") will be taken");
			
			//label not not label+1 because label already points to the branch
			Statement.getStatement(label).visitSuccessors(this.zigma, this.rules);
		}
		else{
			System.out.println("True branch of ("+((ArithExpr)condition).getAxiomString()+") cannot be taken");
		}
		//end true branch
		
		//This is for the branch - false
		
		this.zigma = new store(zigma);
		this.rules = new ArrayArith(rules);
		
		//workaround starts here
		Statement.zigma = this.zigma;
		Statement.rules = this.rules;
		//workaround ends here
		
		if(!(condition instanceof ArithExpr)){
			System.out.println("Condition is not a instance of ArithExpr");
			System.exit(1);
		}
		
		ArithExpr oppositeRule = (ArithExpr)condition;
		oppositeRule = oppositeRule.getOppoAxiom();
		
		
		if(Statement.canBranch(oppositeRule)){
			Statement.rules.addArith(oppositeRule);
			System.out.println("False branch of ("+((ArithExpr)condition).getAxiomString()+") will be taken");
			
			//branchlabel+1 because thats the next statement
			Statement.getStatement(branchLabel + 1).visitSuccessors(this.zigma, this.rules);
		}
		else{
			System.out.println("False branch of ("+((ArithExpr)condition).getAxiomString()+") cannot be taken");
		}
		
		//end false branch
	}
}
